package com.iweb.controller;

import cn.hutool.jwt.JWT;
import com.iweb.commons.ResultEntity;
import com.iweb.model.Admin;
import com.iweb.service.AdminService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * Time :2022/8/16 8:40
 * Author : kriller
 * Project : steam-malls
 */
@RestController
@RequestMapping("admin")
public class AdminController {
    @Resource
    private AdminService adminService;

    @PostMapping("login")
    public ResultEntity<Admin> login(@RequestBody Admin admin, HttpServletResponse resp){
        Admin adminData= adminService.findByAccount(admin.getAdminAccount());
        if (adminData == null) {
            return new ResultEntity<>(3001, "管理员用户不存在", false, null);
        }
        if (!adminData.getAdminPwd().equals(admin.getAdminPwd())) {
            return new ResultEntity<>(3002, "管理员密码不正确", false, null);
        }
        // TOKEN  JWT = json web token
        byte[] key = "iweb".getBytes(); // 不能给人知道
        String token = JWT.create()
                .setPayload("sub", "admin")
                .setPayload("userAccount", adminData.getAdminAccount())
                .setPayload("userId", adminData.getAdminId())
                .setKey(key).sign();
        // session 是通过 cookie 响应的 , 写到响应头
        resp.setHeader("Access-control-expose-headers", "token");
        resp.addHeader("token", token);
        // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwiYWNjb3VudCI6ImFkbWluIiwidXNlcklkIjoxfQ.cFoYNXqwVMJzQS7TdYZPURIWyvUMhyZLV65Y4NvJ2yQ
        return new ResultEntity<>(2000, "管理员登录成功", true, null);
    }
}
